package com.litchi.tutor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.litchi.tutor.common.entity.*;
import com.litchi.tutor.common.util.CopyUtil;
import com.litchi.tutor.common.util.HideSensitiveUtil;
import com.litchi.tutor.common.util.JwtUtil;
import com.litchi.tutor.common.vo.RecruitResp;
import com.litchi.tutor.common.vo.TeacherResp;
import com.litchi.tutor.mapper.DictMapper;
import com.litchi.tutor.mapper.RegionMapper;
import com.litchi.tutor.mapper.TeacherMapper;
import com.litchi.tutor.mapper.UserMapper;
import com.litchi.tutor.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    TeacherMapper teacherMapper;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    RegionMapper regionMapper;

    @Override
    public void createTeacher(Teacher teacher, HttpServletRequest httpServletRequest) {
        // 拷贝基础信息
        Teacher respTeacher = new Teacher();
        BeanUtils.copyProperties(teacher, respTeacher);
        String token = httpServletRequest.getHeader("Authorization");
        // 获取user.id
        Integer id = JwtUtil.getId(token);
        // 获取user.userid 用户id
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        String userid = user.getUserid();
        respTeacher.setUserid(userid);

        save(respTeacher);

    }

    @Override
    public TeacherResp getTeacherByUserId(String userId, HttpServletRequest request) {
        TeacherResp teacherResp = new TeacherResp();
        if (userId != null) { // 如果有传，则查询该用户
            Teacher teacher = getOne(new QueryWrapper<Teacher>().eq("userid", userId));
            BeanUtils.copyProperties(teacher, teacherResp);
            HideSen(teacherResp, teacher);
            getTeachingInfo(teacherResp, teacher);
            return teacherResp;
        } else { // 否则查自己的
            String token = request.getHeader("Authorization");
            Integer id = JwtUtil.getId(token);
            Teacher teacher = getOne(new QueryWrapper<Teacher>().eq("id", id));
            BeanUtils.copyProperties(teacher, teacherResp);
            // 查自己不进行脱敏处理
//            HideSen(teacherResp, teacher);
            getTeachingInfo(teacherResp, teacher);
            return teacherResp;
        }
    }

    private void HideSen(TeacherResp teacherResp, Teacher teacher) {
        String mobile = HideSensitiveUtil.protectedMobile(teacher.getMobile());
        String name = HideSensitiveUtil.protectedName(teacher.getName());
        String wxid = HideSensitiveUtil.protectedWxid(teacher.getWxid());
        teacherResp.setMobile(mobile);
        teacherResp.setName(name);
        teacherResp.setWxid(wxid);
    }


    @Override
    public List<TeacherResp> getTeacher(Long current, Long limit, String birthplaces, String teachingSubjectIds) {
        Page<Teacher> pageTeacher = new Page<>(current,limit);
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(birthplaces)) {
            String[] split = birthplaces.split(",");
            for (String s : split) {
                queryWrapper.or().like("birthplace", s);
            }
        }

        if (!StringUtils.isEmpty(teachingSubjectIds)) {
            String[] split = teachingSubjectIds.split(",");
            for (String s : split) {
                queryWrapper.or().like("teaching_subject_ids", s);
            }
        }

        page(pageTeacher, queryWrapper);
        List<Teacher> records = pageTeacher.getRecords();
        records.forEach(item->{
            String mobile = HideSensitiveUtil.protectedMobile(item.getMobile());
            String name = HideSensitiveUtil.protectedName(item.getName());
            String wxid = HideSensitiveUtil.protectedWxid(item.getWxid());
            item.setMobile(mobile);
            item.setName(name);
            item.setWxid(wxid);
        });

        List<TeacherResp> newList = CopyUtil.copyList1(records, TeacherResp.class);
        newList.forEach(item -> {

            StringBuffer teachingSubjectText = changeIdsToText(item.getTeachingSubjectIds());
            item.setTeachingSubjectText(teachingSubjectText.toString());

            Region region = regionMapper.selectOne(new QueryWrapper<Region>().eq("code", item.getBirthplace()));
            item.setBirthplaceText(region.getName());
        });
        return newList;
    }

    @Override
    public void updateTeacher(Teacher teacher, HttpServletRequest httpServletRequest) {
        Teacher newTeacher = new Teacher();
        String token = httpServletRequest.getHeader("Authorization");
        Integer id = JwtUtil.getId(token);

        BeanUtils.copyProperties(teacher, newTeacher, "userid");
        update(newTeacher, new QueryWrapper<Teacher>().eq("id", id));
    }

    /**
     * 获取teachingxxxText信息
     * @param teacherResp
     * @param teacher
     */
    private void getTeachingInfo(TeacherResp teacherResp, Teacher teacher) {
        StringBuffer teachingGradeIds = changeIdsToText(teacher.getTeachingGradeIds());
        teacherResp.setTeachingGradeText(teachingGradeIds.substring(0, teachingGradeIds.length() - 1));

        StringBuffer teachingScoreIds = changeIdsToText(teacher.getScoreIds());
        teacherResp.setScoreText(teachingScoreIds.substring(0, teachingScoreIds.length() - 1));

        StringBuffer teachingSubjectIds = changeIdsToText(teacher.getTeachingSubjectIds());
        teacherResp.setTeachingSubjectText(teachingSubjectIds.substring(0, teachingSubjectIds.length() - 1));
    }

    public StringBuffer changeIdsToText(String ids) {
        List<Dict> teachingGradeIds = dictMapper.selectBatchIds(Arrays.asList(ids.split(",")));
        StringBuffer stringBuffer = new StringBuffer();
        teachingGradeIds.forEach(item -> {
            stringBuffer.append(item.getText()).append(",");
        });
        return stringBuffer;
    }
}
